跳至主要内容

[Vue CLI] NPM套件安裝範例

TL;DR

介紹如何使用NPM的方式載入外部套件。

參考資料

相關連結


NPM安裝所需套件

如果目前正在nmp run serve的狀態下,需要先使用ctrl+c停用。

接著安裝所需套件:

npm install vee-validate @vee-validate/rules @vee-validate/i18n  --save

官方文件

npm 安裝 VeeValidate

npm 安裝 vee-validate

npm 安裝 VeeValidate rules

npm 安裝 vee-validate的規則(rules)

npm 安裝 VeeValidate i18n

npm 安裝 vee-validate i18n

main.js設定

main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

// 匯入 vee-validate 主套件
import { Field, Form, ErrorMessage, defineRule, configure } from 'vee-validate'

// 匯入 vee-validate 相關規則
import { required, email, min } from '@vee-validate/rules'

// 匯入多國語系的功能
import { localize, setLocale } from '@vee-validate/i18n'

// 匯入繁體中文語系檔案
import zhTW from '@vee-validate/i18n/dist/locale/zh_TW.json'

// 定義驗證規則
defineRule('required', required)
defineRule('email', email)
defineRule('min', min)

// 設定 vee-validate 全域規則
configure({
generateMessage: localize({ zh_TW: zhTW }), // 載入繁體中文語系
validateOnInput: true // 當輸入任何內容直接進行驗證
})

// 設定預設語系
setLocale('zh_TW')

const app = createApp(App).use(router)

// 註冊 vee-validate 三個全域元件
// eslint-disable-next-line vue/multi-word-component-names
app.component('Form', Form)
// eslint-disable-next-line vue/multi-word-component-names
app.component('Field', Field)
app.component('ErrorMessage', ErrorMessage)

app.mount('#app')

在頁面使用

src/views/AboutView.vue
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
<CardTest></CardTest>
<Form v-slot="{ errors, values, validate }" @submit="onSubmit">
{{ errors }} {{ values }}
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<Field id="email" name="email" type="email" class="form-control" :class="{ 'is-invalid': errors['email'] }"
placeholder="請輸入 Email" rules="email|required" v-model="user.email"></Field>
<error-message name="email" class="invalid-feedback"></error-message>
</div>
<button class="btn me-2 btn-outline-primary" type="button" @click="validate">驗證</button>
<button class="btn btn-primary" type="submit">Submit</button>
</Form>
</template>

<script>
import CardTest from '@/components/CardTest.vue'
export default {
components: {
CardTest
},
data () {
return {
user: {}
}
},
methods: {
onSubmit () {
console.log(this.user)
}
},
created () {
console.log(this)
}
}
</script>